package com.example.server.controller;

import com.example.server.entity.User;
import com.example.server.entity.Writer;
import com.example.server.service.UserService;
import com.example.server.service.WriterService;
import com.example.server.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/writers") // 确保路径正确
public class WriterController {

    @Autowired
    private WriterService writerService;

    @Autowired
    private UserService userService;

    @PostMapping("/become-writer")
    public String becomeWriter(@RequestParam String realName, @RequestParam String penName, @RequestHeader("Authorization") String token) throws Exception {
        String tokenUsername = JwtUtil.getUsernameFromToken(token.substring(7)); // 去掉"Bearer "
        User user = userService.getUserByUsername(tokenUsername);
        if (user == null) {
            throw new Exception("用户不存在");
        }
        Writer writer = new Writer();
        writer.setName(realName);
        writer.setPenName(penName);
        writerService.insertWriter(writer);
        user.setIdwriter(writer.getIdwriter());
        userService.updateUser(user);
        return "申请成为作者成功";
    }
}
